﻿using BarcodeDelay.bean;
using BarcodeDelay.utility;
using JTParcrelHelper.bean;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsInputSimulator.Simulator;

namespace BarcodeDelay.logHelp
{
    public class ReplyHelper
    {
        public DateTime dtLastReply = System.DateTime.Now;
        private object lockObj = new object();
        private static ReplyHelper instance;
        public static ReplyHelper Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new ReplyHelper();
                }
                return instance;
            }
        }
        public void replyQQMsg(string roomid, string res, string robotQQ = "")
        {
            try
            {
                //LogHelper.Instance.writeLog("replySuperMsg to_wxid:" + to_wxid+" res:"+ res+" wxid="+ wxid);

                
                string strWechatServer = StoParams.Instance.geQQGetUrl;
                StringBuilder sb = new StringBuilder();
                sb.Append(strWechatServer);
                sb.Append("?token=5aiweiqi&function=Api_SendMsg&c1=");
                sb.Append(robotQQ);
                sb.Append("&c2=2&c3=");
                sb.Append(roomid);
                sb.Append("&c4=");
                sb.Append(roomid);
                sb.Append("&c5="+ res);
                var client = new RestClient(sb.ToString());
                client.Timeout = -1;
                var request = new RestRequest(Method.GET);
                IRestResponse response = client.Execute(request);
        
                //LogHelper.Instance.writeLog("replySuperMsg respone:" + response.Content.ToString());
            }
            catch (Exception ex)
            {
                LogHelper.Instance.writeLog("replySuperMsg ex:" + ex.ToString());
            }
        }

        public bool replySuperMsg(string to_wxid, string res, string mentionUser = "", string wxid = "")
        {
            bool ret = false;
            try
            {
                //LogHelper.Instance.writeLog("replySuperMsg to_wxid:" + to_wxid+" res:"+ res+" wxid="+ wxid);
                ReplyBean replyBean = new ReplyBean();
                replyBean.to_wxid = to_wxid;
                replyBean.res = res;
                replyBean.mentionUser = mentionUser;
                replyBean.wxid = wxid;

                Thread curThread = new Thread(new ParameterizedThreadStart(handleReplyMsg));
                curThread.Start((object)replyBean);
                ret = true;
                //handleReplyMsg(replyBean);

                

            }
            catch (Exception ex)
            {
                LogHelper.Instance.writeLog("replySuperMsg ex:" + ex.ToString());
            }
            return ret;
        }


        public void handleReplyMsg(object replyBean)
        {
            try
            {
                TimeSpan ts = System.DateTime.Now - dtLastReply;
                if(ts.TotalSeconds<3)
                {
                    System.Threading.Thread.Sleep(3000);
                }

                ReplyBean curReplyBean = (ReplyBean)replyBean;
                string strWechatServer = StoParams.Instance.geWePostUrl;
                var client = new RestClient(strWechatServer);
                client.Timeout = -1;
                var request = new RestRequest(Method.POST);
                client.UserAgent = "Apifox/1.0.0 (" + strWechatServer + ")";
                request.AddHeader("Content-Type", "application/json");
                JObject jObjRes = new JObject();

                JObject dataObj = new JObject();
                dataObj["conversation_id"] = curReplyBean.to_wxid;
                dataObj["content"] = curReplyBean.res.Replace("\"", "");
                jObjRes["client_id"] = 1;
                jObjRes["is_sync"] = 1;
                jObjRes["type"] = "WW_SEND_TEXT_MSG";
                jObjRes["data"] = dataObj;
                if (curReplyBean.mentionUser != "" && curReplyBean.wxid != "")
                {
                    JArray jar = new JArray();
                    string[] arr = curReplyBean.wxid.Split(',');
                    foreach (string user in arr)
                    {
                        jar.Add(user);
                    }

                    dataObj["at_list"] = jar;

                    jObjRes["type"] = "WW_SEND_CHATROOM_AT_V2_MSG";

                }

                var body = jObjRes.ToString();
                LogHelper.Instance.writeLog("send msg:" + body.ToString());
                request.AddParameter("application/json", body, ParameterType.RequestBody);
                IRestResponse response = client.Execute(request);
                dtLastReply = System.DateTime.Now;
                //MessageBox.Show(response.Content);
                //Console.WriteLine(response.Content);
                //LogHelper.Instance.writeLog("replySuperMsg respone:" + response.Content.ToString());

                JObject dataRes = (JObject)JsonConvert.DeserializeObject(response.Content.ToString());
                JToken code = dataRes["err_code"];
                if (code.ToString() == "0")
                {
                    //ret = true;
                }
            }
            catch(Exception ex)
            {

            }
        }



        public bool replySuperMsgQW(string to_wxid, string res, string mentionUser = "", string wxid = "")
        {
            bool ret = false;
            try
            {
                //LogHelper.Instance.writeLog("replySuperMsg to_wxid:" + to_wxid+" res:"+ res+" wxid="+ wxid);

                string strWechatServer = StoParams.Instance.geWePostUrl;
                var client = new RestClient(strWechatServer);
                client.Timeout = -1;
                var request = new RestRequest(Method.POST);
                client.UserAgent = "Apifox/1.0.0 (" + strWechatServer + ")";
                request.AddHeader("Content-Type", "application/json");
                JObject jObjRes = new JObject();

                JObject dataObj = new JObject();
                dataObj["conversation_id"] = to_wxid;
                dataObj["content"] = res.Replace("\"", "");
                jObjRes["client_id"] = 1;
                jObjRes["is_sync"] = 1;
                jObjRes["type"] = "WW_SEND_TEXT_MSG";
                jObjRes["data"] = dataObj;
                if (mentionUser != "" && wxid != "")
                {
                    JArray jar = new JArray();
                    string[] arr = wxid.Split(',');
                    foreach (string user in arr)
                    {
                        jar.Add(user);
                    }

                    dataObj["at_list"] = jar;

                    jObjRes["type"] = "WW_SEND_CHATROOM_AT_V2_MSG";

                }

                var body = jObjRes.ToString();
                LogHelper.Instance.writeLog("send msg:" + body.ToString());
                request.AddParameter("application/json", body, ParameterType.RequestBody);
                IRestResponse response = client.Execute(request);
                //MessageBox.Show(response.Content);
                //Console.WriteLine(response.Content);
                //LogHelper.Instance.writeLog("replySuperMsg respone:" + response.Content.ToString());

                JObject dataRes = (JObject)JsonConvert.DeserializeObject(response.Content.ToString());
                JToken code = dataRes["err_code"];
                if (code.ToString() == "0")
                {
                    ret = true;
                }

            }
            catch (Exception ex)
            {
                LogHelper.Instance.writeLog("replySuperMsg ex:" + ex.ToString());
            }
            return ret;
        }
        /// <summary>
        /// 邀请好友进群
        /// </summary>
        /// <param name="to_wxid"></param>
        /// <param name="res"></param>
        /// <param name="mentionUser"></param>
        /// <param name="wxid"></param>
        public void inviteUserMsg(string roomID, string res, string mentionUser = "", string wxid = "")
        {
            try
            {
                //LogHelper.Instance.writeLog("replySuperMsg to_wxid:" + to_wxid+" res:"+ res+" wxid="+ wxid);

                if (res.Replace("{$@}", "").Trim() == "")
                {
                    return;
                }
                string strWechatServer = StoParams.Instance.geWePostUrl;
                var client = new RestClient(strWechatServer);
                client.Timeout = -1;
                var request = new RestRequest(Method.POST);
                client.UserAgent = "Apifox/1.0.0 (" + strWechatServer + ")";
                request.AddHeader("Content-Type", "application/json");
                JObject jObjRes = new JObject();

                JObject dataObj = new JObject();

                dataObj["content"] = res.Replace("\"", "");
                jObjRes["client_id"] = 1;
                jObjRes["type"] = "MT_INVITE_TO_ROOM_MSG";
                jObjRes["data"] = dataObj;

           

                if (mentionUser != "" && wxid != "")
                {
                    JArray jar = new JArray();
                    string[] arr = wxid.Split(',');
                    foreach (string user in arr)
                    {
                        jar.Add(user);
                    }

                    dataObj["member_list"] = jar;
                  

                }
                dataObj["room_wxid"] = roomID;

                var body = jObjRes.ToString();
                //LogHelper.Instance.writeLog("send msg:"+ body.ToString());
                request.AddParameter("application/json", body, ParameterType.RequestBody);
                IRestResponse response = client.Execute(request);
                //MessageBox.Show(response.Content);
                //Console.WriteLine(response.Content);
                //LogHelper.Instance.writeLog("replySuperMsg respone:" + response.Content.ToString());
            }
            catch (Exception ex)
            {
                LogHelper.Instance.writeLog("replySuperMsg ex:" + ex.ToString());
            }
        }



        public void inviteQWUserMsg(string roomID, string res, string mentionUser = "", string wxid = "")
        {
            try
            {
                //LogHelper.Instance.writeLog("replySuperMsg to_wxid:" + to_wxid+" res:"+ res+" wxid="+ wxid);

                /*if (res.Replace("{$@}", "").Trim() == "")
                {
                    return;
                }*/
                string strWechatServer = StoParams.Instance.geWePostUrl;
                var client = new RestClient(strWechatServer);
                client.Timeout = -1;
                var request = new RestRequest(Method.POST);
                client.UserAgent = "Apifox/1.0.0 (" + strWechatServer + ")";
                request.AddHeader("Content-Type", "application/json");
                JObject jObjRes = new JObject();

                JObject dataObj = new JObject();

                //dataObj["content"] = res.Replace("\"", "");
                jObjRes["client_id"] = 1;
                jObjRes["type"] = "WW_INVITE_TO_ROOM_MSG";
                jObjRes["data"] = dataObj;



                if (mentionUser != "" && wxid != "")
                {
                    JArray jar = new JArray();
                    string[] arr = wxid.Split(',');
                    foreach (string user in arr)
                    {
                        jar.Add(user);
                    }

                    dataObj["user_list"] = jar;


                }
                dataObj["conversation_id"] = roomID;

                var body = jObjRes.ToString();
                LogHelper.Instance.writeLog("invite msg:"+ body.ToString());
                request.AddParameter("application/json", body, ParameterType.RequestBody);
                IRestResponse response = client.Execute(request);
                //MessageBox.Show(response.Content);
                //Console.WriteLine(response.Content);
                LogHelper.Instance.writeLog("invite msg respone:" + response.Content.ToString());
            }
            catch (Exception ex)
            {
                LogHelper.Instance.writeLog("replySuperMsg ex:" + ex.ToString());
            }
        }


        /// <summary>
        /// 企业微信
        /// </summary>
        /// <param name="to_wxid"></param>
        /// <param name="res"></param>
        /// <param name="mentionUser"></param>
        /// <param name="wxid"></param>
        /// <returns></returns>
        public bool replyQWSuperMsg(string to_wxid,string res,string mentionUser="",string wxid="")
        {
            bool ret = false;
            try
            {
                //LogHelper.Instance.writeLog("replySuperMsg to_wxid:" + to_wxid+" res:"+ res+" wxid="+ wxid);

                string strWechatServer = StoParams.Instance.geWePostUrl;
                var client = new RestClient(strWechatServer);
                client.Timeout = -1;
                var request = new RestRequest(Method.POST);
                client.UserAgent = "Apifox/1.0.0 ("+ strWechatServer + ")";
                request.AddHeader("Content-Type", "application/json");
                JObject jObjRes = new JObject();

                JObject dataObj = new JObject();
                dataObj["conversation_id"] = to_wxid;
                dataObj["content"] = res.Replace("\"", "");
                jObjRes["client_id"] = 1;
                jObjRes["is_sync"] = 1;
                jObjRes["type"] = "WW_SEND_TEXT_MSG";
                jObjRes["data"] = dataObj;
                if(mentionUser!=""&& wxid!="")
                {
                    JArray jar = new JArray();
                    string[] arr = wxid.Split(',');
                    foreach(string user in arr)
                    {
                        jar.Add(user);
                    }
                   
                    dataObj["at_list"] = jar;
    
                    jObjRes["type"] = "WW_SEND_CHATROOM_AT_V2_MSG";

                }

                var body = jObjRes.ToString();
                LogHelper.Instance.writeLog("send msg:"+ body.ToString());
                request.AddParameter("application/json", body, ParameterType.RequestBody);
                IRestResponse response = client.Execute(request);
                //MessageBox.Show(response.Content);
                //Console.WriteLine(response.Content);
                //LogHelper.Instance.writeLog("replySuperMsg respone:" + response.Content.ToString());

                JObject dataRes = (JObject)JsonConvert.DeserializeObject(response.Content.ToString());
                JToken code = dataRes["err_code"];
                if(code.ToString()=="0")
                {
                    ret = true;
                }

            }
            catch (Exception ex)
            {
                LogHelper.Instance.writeLog("replySuperMsg ex:" + ex.ToString());
            }
            return ret;
        }


        public ArrayList getInternalUserList(int pageNum, int pageSize)
        {
            ArrayList arListRes = new ArrayList();
            try
            {
                //LogHelper.Instance.writeLog("replySuperMsg to_wxid:" + to_wxid+" res:"+ res+" wxid="+ wxid);

                string strWechatServer = StoParams.Instance.geWePostUrl;
                var client = new RestClient(strWechatServer);
                client.Timeout = -1;
                var request = new RestRequest(Method.POST);
                client.UserAgent = "Apifox/1.0.0 (" + strWechatServer + ")";
                request.AddHeader("Content-Type", "application/json");
                JObject jObjRes = new JObject();

                JObject dataObj = new JObject();
                dataObj["page_num"] = pageNum;
                dataObj["page_size"] = pageSize;
                jObjRes["client_id"] = 1;
                jObjRes["type"] = "WW_DATA_INTERNAL_LIST_MSG";
                jObjRes["data"] = dataObj;

                var body = jObjRes.ToString();
                LogHelper.Instance.writeLog("send msg:" + body.ToString());
                request.AddParameter("application/json", body, ParameterType.RequestBody);
                IRestResponse response = client.Execute(request);
                //MessageBox.Show(response.Content);
                //Console.WriteLine(response.Content);
                LogHelper.Instance.writeLog("replySuperMsg respone:" + response.Content.ToString());
                System.Threading.Thread.Sleep(100);
                string[] arr = response.Content.ToString().Split(new string[] { "\"conversation_id\":" }, StringSplitOptions.None);
                StringBuilder sb = new StringBuilder();
                foreach (string strLine in arr)
                {
                    string newLine = strLine;
                    newLine = newLine.Replace("\"", "");
                    if (newLine.StartsWith("R:"))
                    {
                        string left = newLine.Substring(newLine.IndexOf('R'), newLine.IndexOf(',') - newLine.IndexOf('R'));
                        left = left.Replace("\"", "");
                        if (MathUtility.ImpIsNum(left.Replace("R:", "").Trim()) && left.Length > 15)
                        {
                            arListRes.Add(left);
                            sb.AppendLine(left);
                        }

                    }
                }
                LogHelper.Instance.writeLog("get room list:" + sb.ToString());


            }
            catch (Exception ex)
            {
                LogHelper.Instance.writeLog("replySuperMsg ex:" + ex.ToString());
            }
            return arListRes;
        }


        public ArrayList getGroupList(int pageNum,int pageSize)
        {
            ArrayList arListRes = new ArrayList();
            try
            {
                //LogHelper.Instance.writeLog("replySuperMsg to_wxid:" + to_wxid+" res:"+ res+" wxid="+ wxid);

                string strWechatServer = StoParams.Instance.geWePostUrl;
                var client = new RestClient(strWechatServer);
                client.Timeout = -1;
                var request = new RestRequest(Method.POST);
                client.UserAgent = "Apifox/1.0.0 (" + strWechatServer + ")";
                request.AddHeader("Content-Type", "application/json");
                JObject jObjRes = new JObject();

                JObject dataObj = new JObject();
                dataObj["page_num"] = pageNum;
                dataObj["page_size"] = pageSize;
                jObjRes["client_id"] = 1;
                jObjRes["type"] = "WW_DATA_ROOM_LIST_MSG";
                jObjRes["data"] = dataObj;           

                var body = jObjRes.ToString();
                LogHelper.Instance.writeLog("send msg:" + body.ToString());
                request.AddParameter("application/json", body, ParameterType.RequestBody);
                IRestResponse response = client.Execute(request);
                //MessageBox.Show(response.Content);
                //Console.WriteLine(response.Content);
                LogHelper.Instance.writeLog("replySuperMsg respone:" + response.Content.ToString());
                System.Threading.Thread.Sleep(100);
                string[] arr = response.Content.ToString().Split(new string[] { "\"conversation_id\":" }, StringSplitOptions.None);
                StringBuilder sb = new StringBuilder();
                foreach (string strLine in arr)
                {
                    string newLine = strLine;
                    newLine = newLine.Replace("\"", "");
                    if (newLine.StartsWith("R:"))
                    {
                        string left = newLine.Substring(newLine.IndexOf('R'), newLine.IndexOf(',') - newLine.IndexOf('R'));
                        left = left.Replace("\"", "");
                        if (MathUtility.ImpIsNum(left.Replace("R:", "").Trim()) && left.Length > 15)
                        {
                            arListRes.Add(left);
                            sb.AppendLine(left);
                        }

                    }
                }
                LogHelper.Instance.writeLog("get room list:" + sb.ToString());


            }
            catch (Exception ex)
            {
                LogHelper.Instance.writeLog("replySuperMsg ex:" + ex.ToString());
            }
            return arListRes;
        }


        public void replyMsg(string msg, GroupPos groupPos)
        {
            //LogHelper.Instance.writeLog("replyMsg begin");
            lock (lockObj)
            {
                try
                {
                    Point p = groupPos.inputPos;
                    LogHelper.Instance.writeLog("write pos:x=" + p.X.ToString() + "y=" + p.Y.ToString());
                    //Point p = WindowsInputSimulator.Simulator.InputSimulator.GetMousePosition();
                    //Clipboard.Clear();
                    Clipboard.SetDataObject(msg, true, 10, 200);
                    //InputSimulator.SimualteMouseClick(VirtualKeyCode.LBUTTON, p);

                    InputSimulator.SimualteMouseClick(VirtualKeyCode.LBUTTON, InputSimulator.ScreenPositionToInputPosition(p.X, p.Y));
                    System.Threading.Thread.Sleep(100);
                    InputSimulator.SimulateModifiedKeyStroke(VirtualKeyCode.CONTROL, VirtualKeyCode.VK_V);
                    InputSimulator.SimulateKeyDown(VirtualKeyCode.RETURN);
                    System.Threading.Thread.Sleep(100);
                }
                catch (Exception ex)
                {
                    LogHelper.Instance.writeLog("replyMsg ex:"+ex.ToString());
                    //System.Windows.Forms.MessageBox.Show("writeLog error:"+ ex.ToString());
                }
            }
            
        }


        public void readMsg(GroupPos groupPos,out string msg)
        {
            msg = "";
            lock (lockObj)
            {
                try
                {
                    Point p = groupPos.readPos;

                    InputSimulator.SimualteMouseClick(VirtualKeyCode.LBUTTON, InputSimulator.ScreenPositionToInputPosition(p.X, p.Y));

                    InputSimulator.SimulateModifiedKeyStroke(VirtualKeyCode.CONTROL, VirtualKeyCode.VK_A);
                    InputSimulator.SimulateModifiedKeyStroke(VirtualKeyCode.CONTROL, VirtualKeyCode.VK_C);
                    System.Threading.Thread.Sleep(50);

                    IDataObject iData = Clipboard.GetDataObject();
                    // 将数据与指定的格式进行匹配，返回bool
                    if (iData.GetDataPresent(DataFormats.Text))
                    {
                        // GetData检索数据并指定一个格式
                        msg = (string)iData.GetData(DataFormats.Text);
                    }
                    else
                    {
                        LogHelper.Instance.writeLog("剪贴板中数据不可转换为文本");
                    }
                }
                catch (Exception ex)
                {
                    //System.Windows.Forms.MessageBox.Show("writeLog error:"+ ex.ToString());
                }
            }

        }



    }
}
